class ImageFactsController < ApplicationController
  def show_raw
    begin
      ifact = ImageFact.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      no_image
      return
    end
    
    if(ifact.images.count<1)
      no_image
      return
    end

    image = ifact.images[0]
    file = File.join(image.folder.path, image.leaf)
    
    send_data(IO.read(file), :type => "image/jpg", :filename => image.leaf, :disposition => 'inline')
  end
  
  # randomly chooses two valid image facts to compare and delivers uses the id delivered. No pre-tagged requirement.
  def random_compare
    (left, right) = ImageFact.random(2)
    search_compare = Tag.invoke params[:search_compare]
    url_suffix = (search_compare.id>0 ? "?search_compare=#{search_compare.id}" : '')

    redirect_to "/image_facts/compare/#{params[:id]}/#{left.id}/#{right.id}" + url_suffix, :status => 301
  end
  
  def compare
    @tag = Tag.invoke(params[:tag])
    @left = ImageFact.find(params[:left], :include => :images)
    @right = ImageFact.find(params[:right], :include => :images)
    @search_compare = params[:search_compare].to_i
    
    render
  end

  def search_compare
    @tag = Tag.invoke params[:id]
  
    left  = ImageFact.tag_sample(@tag.id)
    right = ImageFact.tag_sample(@tag.id, :blocklist => [left.id])
    redirect_to "/image_facts/compare/#{params[:id]}/#{left.id}/#{right.id}?search_compare=#{@tag.id}", :status => 301
  end
  
  # Simple version of search. Similar to Subjectivity v1 "linear search"
  def search1
    @tag = Tag.invoke params[:id]
      
    @votes = Vote.find_all_by_tag_id(@tag.id, :order => "perc desc, (plus_votes/minus_votes) desc, random()",
        :include => :image_fact, :limit => 500)
        
    # Kick out all vote examples where we don't have the associated image.. but keep the "plimsoll" in the list where it belongs.
    @votes.delete_if { |v| Image.count(:conditions => {:image_fact_id => v.image_fact_id})<1 && !v.image_fact.plimsoll?}
    
    render
  end
  
  private
  
  def no_image
    redirect_to "/images/no_image.jpg"
  end

end